package cn.sz.hy.adapter.top;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Text;

import cn.sz.hy.adapter.MouseAdapterBasic;
import cn.sz.hy.common.Globel;
import cn.sz.hy.logic.strategy.StrategyFactory;
import cn.sz.hy.logic.strategy.impl.XlsStrategy;
import cn.sz.hy.logic.strategy.vo.BasicVo;
import cn.sz.hy.logic.strategy.vo.SheetItem;
import cn.sz.hy.logic.strategy.vo.TableVo;
import cn.sz.hy.ui.frame.CenterPanel;
import cn.sz.hy.ui.widget.center.Row;

public class ExecuteButtonAdapter extends MouseAdapterBasic {
	private XlsStrategy xs;
	private String path;
	private CenterPanel centerPanel;

	@Override
	protected void execute(MouseEvent e) {
		Combo executeList = (Combo) eBus.getComponent(Globel.EXECUTE_LIST_ID);
		centerPanel = (CenterPanel) eBus
				.getComponent(Globel.CENTER_PANEL_ID);
		Text detPath = (Text) eBus
				.getComponent(Globel.DET_TEXTFIELDE_ID);
		xs = StrategyFactory.getStrategy(executeList.getSelectionIndex());
		path = detPath.getText();

		if (path == null || path.equals("")) {
			detPath.setText("");
			return;
		}
		
		boolean result = xs.execute(getBasicVo());
		MessageBox alert = (MessageBox) eBus.getComponent(Globel.MESSAGE_BOX_ID);
		
		if(result){
		    alert.setMessage("表格合并成功");
		}else{
		    alert.setMessage("表格合并失败");
		}
		
        alert.open();
	}

	private BasicVo getBasicVo() {
		BasicVo vo = new BasicVo();
		vo.setDet(path);
		vo.setSheetIndex(0);
		List<SheetItem> columns = new ArrayList<SheetItem>();
		TableVo backup = eBus.getTableVo(Globel.BACKUP);

		List<Row> rows = centerPanel.getRows();
		for (Row row : rows) {
			if (row.getVisible()) {
				insertItem(columns, backup, row);
			}
		}

		vo.setDetColumn(columns);
		return vo;
	}

	private void insertItem(List<SheetItem> columns, TableVo backup,
			Row row) {
		List<SheetItem> backItems = backup.getColumns();
		String name = row.getText().getText();
		int type = row.getLink().getSelectionIndex();
		switch (type) {
		case Globel.NONE_LINK:
			SheetItem item = row.getItem();
			if(item == null){
				return;
			}
			item.setName(name);
			item.setLinkType(type);
			columns.add(item);
			break;
		case Globel.KEY_LINK:
			SheetItem key = row.getItem();
			if(key == null){
				return;
			}
			SheetItem mappingIten = backItems.get(
					row.getBackup().getSelectionIndex());
			key.setMappingItem(mappingIten, Globel.KEY_LINK);
			key.setName(name);
			mappingIten.setLinkType(type);
			columns.add(key);
			break;
		case Globel.INSERT_LINK:
			SheetItem insertItem = backItems.get(
					row.getLink().getSelectionIndex());
			insertItem.setLinkType(type);
			insertItem.setName(name);
			columns.add(insertItem);
			break;
		default:
			break;
		}
	}

}
